package algorithm.leetcode.simple;

/*
 给你两个二进制字符串，返回它们的和（用二进制表示）。
 */

/**
 * @author jack.wu
 * @version 1.0
 * @date 2020/9/30
 */
public class Question67 {

    public static void main(String[] args) {
        String a = "11", b = "1";
        Question67 question = new Question67();
        String s = question.addBinary(a, b);
        System.out.println(s);
    }

    public String addBinary(String a, String b) {
        StringBuilder sb = new StringBuilder();
        int aLen = a.length() - 1;
        int bLen = b.length() - 1;
        int carry = 0;

        while (aLen >= 0 || bLen >= 0) {
           int sum = carry;
           if (aLen >= 0) {
               sum += a.charAt(aLen--) - '0';
           }
           if (bLen >= 0) {
               sum += b.charAt(bLen--) - '0';
           }
           carry = sum / 2;
           sb.append(sum % 2);
        }
        if (carry == 1) {
            sb.append(carry);
        }
        return sb.reverse().toString();
    }
}
